package com.huahua.api.service.impl;

import com.huahua.api.entity.param.UrlCodecParam;
import com.huahua.api.exception.CommonException;
import com.huahua.api.service.UrlCodecService;
import com.huahua.api.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.net.url.UrlDecoder;
import org.dromara.hutool.core.net.url.UrlEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * URL编码解码服务实现
 */
@Slf4j
@Service
public class UrlCodecServiceImpl implements UrlCodecService {

    @Override
    public Mono<String> process(UrlCodecParam param) {
        return Mono.fromCallable(() -> {
            CheckUtil.checkStrNotBlank(param.getContent(), new CommonException("内容不能为空"));
            CheckUtil.checkStrNotBlank(param.getOperation(), new CommonException("操作类型不能为空"));

            Charset charset;
            try {
                charset = Charset.forName(param.getCharset());
            } catch (Exception e) {
                throw new CommonException("不支持的字符集：" + param.getCharset());
            }

            String result;
            switch (param.getOperation()) {
                case "encode":
                    // URL编码
                    result = UrlEncoder.encodeAll(param.getContent(), charset);
                    break;
                case "decode":
                    // URL解码
                    result = UrlDecoder.decode(param.getContent(), charset);
                    break;
                default:
                    throw new CommonException("不支持的操作类型，请使用encode或decode");
            }

            log.debug("URL编码解码完成，类型：{}，字符集：{}", param.getOperation(), param.getCharset());
            return result;
        });
    }
}
